package middleware

import (
	"net/http"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"

	"cs/util"
)

// JWT is jwt middleware
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "fail", "message": "token不能为空"})
			c.Abort()
			return
		}

		claims, err := util.ParseToken(token)
		if err != nil {
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				c.JSON(http.StatusUnauthorized, gin.H{"status": "fail", "message": "token失效"})
				c.Abort()
				return
			default:
				c.JSON(http.StatusUnauthorized, gin.H{"status": "fail", "message": "token验证失败"})
				c.Abort()
				return
			}
		}

		c.Set("user_id", claims.UserId)
		c.Next()
	}
}
